<template>
  <el-container class="me-top">
    <el-header>
      <el-row>
        <el-col :span="18" style="text-align: left;">
          <el-form ref="form" :model="formInline" :inline="true">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" />
            </el-form-item>

            <el-button icon="el-icon-search" circle @click="search" />
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add">添加</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">批量删除</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="selectedRows">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="name" label="资源名称" align="center" />
        <el-table-column prop="url" label="资源地址" align="center" />
        <el-table-column prop="descs" label="资源描述" align="center" />
        <el-table-column prop="sn" label="资源权限" align="center" />
        <el-table-column prop="menu.name" label="权限菜单" align="center" />
        <el-table-column fixed="right" label="操作" align="center"  width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit-outline" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- :current-page="2"-->
      </div>
    </el-main>
    <!--  新增、编辑-->
    <el-dialog title="新增权限" center width="23%" :visible.sync="dialogFormVisible" style="padding-right: 15px;">
      <el-form ref="addForm" :model="addForm" label-width="100px"  status-icon :rules="rules">
      <input v-model="addForm.id" type="hidden">
      <el-form-item prop="name" label="资源名称">
        <el-input v-model="addForm.name"  />
      </el-form-item>
      <el-form-item prop="url" label="资源地址">
        <el-input v-model="addForm.url"   />
      </el-form-item>
      <el-form-item prop="descs" label="资源描述">
        <el-input v-model="addForm.descs" type="textarea" :rows="3"   />
      </el-form-item>
      <el-form-item prop="sn" label="资源">
        <el-input v-model="addForm.sn"   />
      </el-form-item>
      <el-form-item prop="menuId " label="菜单">
          <el-cascader size="small"
                       placeholder="可搜索关键字"
                       @change="getMenuId"
                       filterable
                       :props="{ checkStrictly: true }" :options="options" clearable  />
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
export default {
  data() {
    return {
      flag: true,
      addForm: {
        id: '',
        name: '',
        url: '',
        descs: '',
        sn: '',
        menu: {},
      },
      page: 1, // 第几页
      size: 10, // 每页条数
      total: 0,
      pageSizes: [5, 10, 15, 20],
      tableData: [],
      formInline: {
        name: '',
        date: ''
      },
      dialogFormVisible: false,
      selectRows: {},
      options : [],
      menuId : '',
      rules: {
        name : [
          { required: true, message: '请输入资源名称', trigger: 'blur' }
        ],
        url : [
          { required: true, message: '请输入资源地址', trigger: 'blur' }
        ],
        descs : [
          { required: true, message: '请输入资源描述', trigger: 'blur' }
        ],
        sn : [
          { required: true, message: '请输入资源', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadListData()
    this.findMenuList()//加载菜单下拉框
  },
  methods: {
    getMenuId(value) {
      this.menuId = value[value.length-1]
      console.log(this.menuId)
    },
    search() {
      this.loadListData()
    },
    submit() {
      const axios = this.$http //定义请求
      const msg= this.$message //定义消息弹框
      this.addForm.menu = {id:this.menuId}
      if (this.addForm.id) { // 修改
        axios.put('/permission/update', this.addForm).then((res) => {
          if (res.data.success) {
            msg.success(res.data.message)
            this.loadListData()
            this.dialogFormVisible = false
        } else {
             // eslint-disable-next-line no-undef
          msg.error('修改失败[' + error.message + ']')
        }
        }).catch(error => {
          console.log(error)
        })
      } else { // 添加
        const axios = this.$http //定义请求
        const msg= this.$message //定义消息弹框
        axios.post('/permission/insert', this.addForm).then((res) => {
          if (res.data.success) {
            msg.success(res.data.message)
            this.loadListData()
            this.dialogFormVisible = false
          } else {
            // eslint-disable-next-line no-undef
            msg.error('添加失败[' + error.message + ']')
          }
         }).catch(error => {
          console.log(error)
         })
      }
    },
    add() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
      })
      for(let key in this.addForm){
        this.addForm[key] = ''
      }
    },
    edit(row) {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.addForm = Object.assign({}, row)
      })

    },
    remove(row) {
      let axios = this.$http //定义请求
      let msg= this.$message //定义消息弹框
      axios.delete('/permission/deleteById/' + row.id).then(res => {
      if (res.data.success) {
        msg.success(res.data.message)
        this.loadListData()
      } else {
      // eslint-disable-next-line no-undef
        msg.error('删除失败[' + error.message + ']')
      }
      }).catch(error => {
        msg.error('删除失败[' + error.message + ']')
      })
    },
    BatchRemove() {
      let axios = this.$http //定义请求
      let msg= this.$message //定义消息弹框
      const ids = this.selectRows.map(function(obj, index, arr) {
        return obj.id
      })
      console.log(ids.toString())
      axios.post('/permission/batchDeleteByIds', { ids: ids }).then(res => {
      if (res.data.success) {
        msg.success(res.data.message)
        this.loadListData()
      } else {
        // eslint-disable-next-line no-undef
        msg.error('删除失败[' + error.message + ']')
      }
      }).catch(error => {
        msg.error('删除失败[' + error.message + ']')
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.loadListData()
    },
    handleCurrentChange(currentPage) {
      this.page = currentPage
      this.loadListData()
    },
    findMenuList() {
      const axios = this.$http // 定义请求
      this.loading = true
      // vue加载完成，发送ajax请求动态获取数据
      const param = {
        'isPagination': false
      }
      axios.post('/menu/findForList', param).then((res) => {
        this.options = [] //清出之前的数据
        this.menuJsonConvert(res.data.data.result)
      }).catch(error => {
        console.log(error)
      })
    },
    menuJsonConvert(json){
      let selectData = json
      for (let i = 0; i < selectData.length; i++) {
        let options = {}
        options["value"] = selectData[i].id
        options["label"] = selectData[i].name
        if (selectData[i].children){
          options["children"] = []
          for (let j = 0; j < selectData[i].children.length ; j++) {
            options["children"].push({"value":selectData[i].children[j].id,"label":selectData[i].children[j].name})
            this.menuJsonConvert(selectData[i].children[j].children)
          }
        }
        this.options.push(options);
      }
    },
    loadListData() {
      let axios = this.$http //定义请求
      this.loading = true
      // vue加载完成，发送ajax请求动态获取数据
      const param = {
        'pageNo': this.page,
        'pageSize': this.size,
        'keyWord': this.formInline.name
      }
      axios.post('/permission/findForList', param).then((res) => {
        this.tableData = res.data.data.result
        this.total = res.data.data.total
        this.page = res.data.data.pageNo
        }).catch(error => {
        console.log(error)
})
    },
    selectedRows(rows) {
      console.log(rows)
      if (rows.length > 0) {
        this.flag = false
        this.selectRows = rows
      } else {
        this.flag = true
      }
    }
  }
}
</script>

<style scoped>
.me-top{
  padding-top: 20px;
}
</style>
